package com.qf.service;

import com.qf.constant.CacheConstants;
import com.qf.constant.StrategyConstants;
import com.qf.feign.CacheFeign;
import com.qf.model.StandardSubmit;
import com.qf.util.PushMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 扣费策略  发送目标手机号运营商不同  费用不同
 */
@Service(value = "fee")
@Slf4j
public class FeeServiceImpl implements FilerChainService {

    @Autowired
    private CacheFeign cacheFeign;

    @Autowired
    private PushMsgUtil pushMsgUtil;

    @Override
    public boolean strategy(StandardSubmit standardSubmit) {
        log.info("[策略模块 - 扣费策略]，开始执行，StandardSubmit={}",standardSubmit);
        // 类似将指定的金额,冻结起来(预扣费)
        //1. 查询当前客户存储在缓存模块中的剩余费用
        Object feeObj = cacheFeign.hget(CacheConstants.CACHE_PREFIX_CLIENT + standardSubmit.getClientID(), "fee");
        if (StringUtils.isEmpty(feeObj)){
            log.info("[策略模块 - 扣费策略]，用户账户信息无法获得，StandardSubmit={}",standardSubmit);
            return false;
        }
        //z账户余额
        Long totalFee = Long.parseLong(String.valueOf(feeObj));

        //2. 查询当前短信需要的费用
        Long fee = standardSubmit.getFee();

        //3. 判断客户 剩余费用 >= 短信需要的费用
        if(totalFee >= fee){
            //4. 满足要求,开始扣费(incr)
            totalFee = cacheFeign.hincr(CacheConstants.CACHE_PREFIX_CLIENT + standardSubmit.getClientID(), "fee", -fee);

            //5. 扣费完成之后,用户的剩余金额 < 0
            if (totalFee < 0){
                //6. 如果扣除后,金额 < 0  -- 用户金额不足,将扣除的费用再加回缓存,记录日志,发送消息,return false
                log.info("[策略模块 - 扣费策略] 扣费策略执行失败  用户剩余金额不足  StandardSubmit={}",standardSubmit);
                cacheFeign.hincr(CacheConstants.CACHE_PREFIX_CLIENT+standardSubmit.getClientID(),"fee",fee);
                pushMsgUtil.sendLog(standardSubmit, StrategyConstants.STRATEGY_ERROR_FEE);
                pushMsgUtil.pushReport(standardSubmit, StrategyConstants.STRATEGY_ERROR_FEE);
                return false;
            }
            //7. 如果可以成功发送,记录预扣除的费用.(冻结的费用)   冻结费用的key, CUSTOMER_FEE:  拼接上客户的ID
            cacheFeign.incr(CacheConstants.CACHE_PREFIX_CUSTOMER_FEE + standardSubmit.getClientID(), -fee);
            // 冻结费用成功，记录日志，return true
            log.info("[策略模块 - 扣费策略] 扣费成功  StandardSubmit={}",standardSubmit);
            return true;
        }

        // 如果第一个if没进去,说明用户剩余金额不足
        log.info("[策略模块 - 扣费策略] 扣费策略执行失败  用户剩余金额不足 StandardSubmit={}",standardSubmit);
        pushMsgUtil.sendLog(standardSubmit, StrategyConstants.STRATEGY_ERROR_FEE);
        pushMsgUtil.pushReport(standardSubmit, StrategyConstants.STRATEGY_ERROR_FEE);
        return false;
    }
}
